import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Wrapper ,HotWordWrapper,HotCourseWrapper} from './style'
import {connect} from 'react-redux'
import {getSearchAction, getSuggestionAction,setSuggestion} from '@/store/actionCreator/search'
import { rootState } from '@/store'
import {useNavigate} from 'react-router-dom'
import HotCourseItem from '@/components/HotCourseItem'
import debounce from 'lodash/debounce'
import SuggestionItem from './suggestionItem'
interface searchProps{
    loading:boolean,
    hotWord:any[],
    hotCourse:any[],
    suggestionList:any[],
    getSearchActionDispatch:()=>void,
    getSuggestionListDispatch:(keyword:string)=>void,
    setSuggestionListEmptyDispatch:(empty:[])=>void
}

const Search:React.FC<searchProps> = (props) => {

    const navigate=useNavigate()
    const {loading,hotWord,hotCourse,suggestionList}=props
    const {getSearchActionDispatch,
        getSuggestionListDispatch,
        setSuggestionListEmptyDispatch,
    }=props
    useEffect(()=>{
        if(!loading){
            getSearchActionDispatch()
        }
    },[])

    // 搜索框
    const queryRef:any=useRef();
    // 输入进搜索框的值
    const [query,setQuery]=useState('')
    // 用于搜索的值
    const [newQuery,setNewQuery]=useState('')
    // 负责处理 搜索框值变化 设置query
    const handleChange=(e:React.ChangeEvent<HTMLInputElement>)=>{
        let val =e.target.value
        setQuery(val)
    }
    // 负责处理 真正进行搜索请求的值
    const handleNewQuery=(q:string)=>{
        setNewQuery(q)
        // console.log(q,'-',newQuery,'防抖ending',new Date());
    }
    // 视图在更新 每次都会执行 产生的是不同的handledebounce函数了
    // const handleNewQueryDebounce=debounce(handleNewQuery,3000);
    // useCallback只初始化一次该函数 下次不再产生新的函数 为了共享闭包timerId
    const handleNewQueryDebounce= useCallback(debounce(handleNewQuery,200),[]);

    useEffect(()=>{
        // 挂载自动聚焦
        queryRef.current.focus();
    },[])

    useEffect(()=>{
        // 负责newQuery的更新
        // console.log(query,'防抖ing',new Date());
        handleNewQueryDebounce(query)
        // 当搜索框的值改变时
    },[query])

    useEffect(()=>{
        // console.log("校正",newQuery,'-',query);
        let curQuery =query;
        // 校正 用于搜索的值 和我们输入的值
        if(newQuery!==query){
            curQuery=newQuery;
            queryRef.current.value=newQuery;
        }
        setQuery(curQuery)
        // 当newQuery更新时
    },[newQuery])
    useEffect(()=>{
        // 是否有必要进行请求
        if(newQuery.trim()){
            // console.log("request:"+newQuery+'--'+new Date());
            getSuggestionListDispatch(newQuery)
        }else{
            setSuggestionListEmptyDispatch([])
        }
    },[newQuery])

    const displayStyle = query ? { display: "block" } : { display: "none" };
    const clearQuery = () => {
        setQuery("");
        queryRef.current.value = "";
        queryRef.current.focus();
    };
    const hotDisplayStyle= (suggestionList&&suggestionList.length||query)?{ display: "none" }:{ display: "block" }
    return (
        <Wrapper>
            <div className="search_bar_wrapper">
                <div className="search_bar">
                    <div className="search_icon">
                        <i className="iconfont icon-sousuo"></i>
                    </div>
                    <div className="search_input">
                        <input type="text" placeholder='8.8全民运动节'
                            ref={queryRef}
                            onChange={handleChange}
                        />
                    </div>
                    <div className="icon_delete" 
                        style={displayStyle}
                        onClick={clearQuery}
                    >
                        <i className="iconfont icon-qingchu"></i>
                    </div>
                </div>
                <div className="search_cancel"
                    onClick={()=>navigate(-1)}
                >
                    取消
                </div>
            </div>
            <div className="hot_wrapper"
                style={hotDisplayStyle}
            >
                <HotWordWrapper>
                    <div className="wrapper_title">搜索发现</div>
                    <div className="hotword_wrapper">
                        {hotWord.slice(0,9).map((item,index)=>{
                            return(
                                <div className="hotword_item" key={index}>{item.value}</div>
                            )
                        })}
                    </div>
                </HotWordWrapper>
                <HotCourseWrapper>
                    {
                        hotCourse.map((item,index)=>{
                            // console.log(item);
                            return(
                                <div className='hotcourse_wrapper' key={index}>
                                    <div className="hotcourse_title">{item.rankTitle}</div>
                                    {item.data.map((hotCourse:any,index:any)=>{
                                        // console.log(hotCourse);
                                        return(
                                            // <></>
                                            <HotCourseItem key={index} hotCourse={hotCourse}/>
                                        )
                                    })}
                                </div>
                            )
                        })
                    }   
                </HotCourseWrapper>
            </div>
            <div className="suggestion_list_wrapper">
                {
                    suggestionList.map((item,index)=>{
                        return(
                            <SuggestionItem key={index} name={item.name}/>
                        )
                    })
                }
            </div>
        </Wrapper>
    )
}
const mapStateToProps=(state:rootState)=>({
    loading:state.searchData.loading,
    hotWord:state.searchData.hotWord,
    hotCourse:state.searchData.hotCourse,
    suggestionList:state.searchData.suggestionList,
})
const mapDispatchToProps=(dispatch:any)=>({
    getSearchActionDispatch(){
        dispatch(getSearchAction())
    },
    getSuggestionListDispatch(keyword:string){
        dispatch(getSuggestionAction(keyword))
    },
    setSuggestionListEmptyDispatch(empty:[]){
        dispatch(setSuggestion(empty))
    }
})
export default  connect(mapStateToProps,mapDispatchToProps)(React.memo(Search))
